package com.xuxingcan.findmyvoice.Fragment;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.GetDataCallback;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.rey.material.widget.ProgressView;
import com.xuxingcan.findmyvoice.Activity.BaseActivity;
import com.xuxingcan.findmyvoice.Activity.DetailActivity;
import com.xuxingcan.findmyvoice.Model.ReceiveMessageModel;
import com.xuxingcan.findmyvoice.R;
import com.xuxingcan.findmyvoice.Util.AudioUtil;
import com.xuxingcan.findmyvoice.Util.LeanCloudUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2016/3/28.
 */
public class SquareFragment extends Fragment {
    private Handler mHandler;
    private Context mContext;
    private PullToRefreshListView mPullToRefreshListView;
    private View rootView;
    private MyAdapter2 myAdapter;
    private DisplayImageOptions options = new DisplayImageOptions.Builder()
            .showImageOnLoading(R.drawable.test)          // 设置图片下载期间显示的图片
            .showImageForEmptyUri(R.drawable.test)  // 设置图片Uri为空或是错误的时候显示的图片
            .showImageOnFail(R.drawable.test)       // 设置图片加载或解码过程中发生错误显示的图片
            .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
            .cacheOnDisk(true)                          // 设置下载的图片是否缓存在SD卡中
            .build();                                   // 创建配置过得DisplayImageOption对象
    private ArrayList<ReceiveMessageModel> messageModelArrayList;

    public SquareFragment(Context mContext) {
        this.mContext = mContext;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ArrayList<ReceiveMessageModel> tempList;
        if (messageModelArrayList.size() > 10) {
            tempList = new ArrayList<>();
            for (int i = 0; i < 10; i++) {
                tempList.add(messageModelArrayList.get(i));
            }
        } else {
            tempList = messageModelArrayList;
        }
        try {
            String s = new Gson().toJson(tempList);
            File mFile = new File(mContext.getCacheDir(), "MessageList");
            FileOutputStream fs = new FileOutputStream(mFile);
            fs.write(s.getBytes(), 0, s.getBytes().length);
            fs.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.obj instanceof SetPlayProgress) {
                    ((SetPlayProgress) msg.obj).mProgressView.setProgress(((SetPlayProgress) msg.obj).progress);
                }
            }
        };
        try {
            File mFile = new File(mContext.getCacheDir(), "MessageList");
            InputStream in = new FileInputStream(mFile);
            byte[] strBuffer = new byte[in.available()];
            in.read(strBuffer, 0, in.available());
            messageModelArrayList = new Gson().fromJson(new String(strBuffer),
                    new TypeToken<ArrayList<ReceiveMessageModel>>() {
                    }.getType());
            in.close();
        } catch (Exception e) {

        }
        rootView = inflater.inflate(R.layout.fragment_square, container, false);
        initView();
        initClick();
        return rootView;
    }

    private void initView() {
        mPullToRefreshListView = (PullToRefreshListView) rootView.findViewById(R.id.refresh_list_view);
        mPullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        messageModelArrayList = new ArrayList<>();
        myAdapter = new MyAdapter2();
        mPullToRefreshListView.setAdapter(myAdapter);
    }

    private void initClick() {
        mPullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                ((BaseActivity) getActivity()).showShortToast("onPullDownToRefresh");
                LeanCloudUtil.getMessageQueue(0, 20, messageModelArrayList.size() == 0 ? null : messageModelArrayList.get(0).getCreateDate(), true,
                        new LeanCloudUtil.getMsgCallBack() {
                            @Override
                            public void onError(Exception e) {
                                ((BaseActivity) getActivity()).showShortToast("onError");
                                mPullToRefreshListView.onRefreshComplete();
                            }

                            @Override
                            public void onSuccess(ArrayList<ReceiveMessageModel> messageModels) {
                                ((BaseActivity) getActivity()).showShortToast("onSuccess");
                                if (messageModelArrayList.size() != 0) {
                                    if (messageModels.size() == 0 || (messageModels.size() == 1 && messageModels.get(0).getId().equals(messageModelArrayList.get(0).getId()))) {
                                        ((BaseActivity) getActivity()).showShortToast("没有更多内容了");
                                        mPullToRefreshListView.onRefreshComplete();
                                        return;
                                    }
                                }
                                for (ReceiveMessageModel msg : messageModels) {
                                    messageModelArrayList.add(0, msg);
                                }
                                myAdapter.notifyDataSetChanged();
                                mPullToRefreshListView.onRefreshComplete();
                            }
                        });
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                ((BaseActivity) getActivity()).showShortToast("onPullUpToRefresh");
                if (messageModelArrayList.size() == 0) {
                    mPullToRefreshListView.onRefreshComplete();
                    return;
                }
                LeanCloudUtil.getMessageQueue(0, 20, messageModelArrayList.get(messageModelArrayList.size() - 1).getCreateDate(), false,
                        new LeanCloudUtil.getMsgCallBack() {
                            @Override
                            public void onError(Exception e) {
                                ((BaseActivity) getActivity()).showShortToast("onError");
                                mPullToRefreshListView.onRefreshComplete();
                            }

                            @Override
                            public void onSuccess(ArrayList<ReceiveMessageModel> messageModels) {
                                ((BaseActivity) getActivity()).showShortToast("onSuccess");
                                if (messageModelArrayList.size() != 0) {
                                    if (messageModels.size() == 0 || (messageModels.size() == 1 && messageModels.get(0).getId().equals(messageModelArrayList.get(messageModelArrayList.size() - 1).getId()))) {
                                        ((BaseActivity) getActivity()).showShortToast("没有更多内容了");
                                        mPullToRefreshListView.onRefreshComplete();
                                        return;
                                    }
                                }
                                for (ReceiveMessageModel msg : messageModels) {
                                    messageModelArrayList.add(0, msg);
                                }
                                myAdapter.notifyDataSetChanged();
                                mPullToRefreshListView.onRefreshComplete();
                            }
                        });
            }
        });
        if (messageModelArrayList.size() == 0) {
            mPullToRefreshListView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mPullToRefreshListView.setRefreshing();
                }
            }, 1000);
        }
    }

    private class ViewHolder {
        TextView time;
        TextView data;
        ImageView image;
        View progress;
        View playLayout;
        ImageView play;
        TextView lin1;
        TextView lin2;
        TextView audioTime;
    }

    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return messageModelArrayList.size();
        }

        @Override
        public Object getItem(int position) {
            return messageModelArrayList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater mInflater = LayoutInflater.from(mContext);
            ViewHolder mViewHolder = null;
            if (convertView == null) {
                mViewHolder = new ViewHolder();
                convertView = mInflater.inflate(R.layout.square_item, null);
                mViewHolder.time = (TextView) convertView.findViewById(R.id.time);
                mViewHolder.data = (TextView) convertView.findViewById(R.id.data);
                mViewHolder.image = (ImageView) convertView.findViewById(R.id.image);
                mViewHolder.progress = convertView.findViewById(R.id.progress);
                mViewHolder.playLayout = convertView.findViewById(R.id.play_layout);
                mViewHolder.play = (ImageView) convertView.findViewById(R.id.play);
                mViewHolder.lin1 = (TextView) convertView.findViewById(R.id.line1);
                mViewHolder.lin2 = (TextView) convertView.findViewById(R.id.line2);
                mViewHolder.audioTime = (TextView) convertView.findViewById(R.id.audio_time);
                convertView.setTag(mViewHolder);
            } else {
                mViewHolder = (ViewHolder) convertView.getTag();
            }
            ReceiveMessageModel msg = messageModelArrayList.get(position);
            mViewHolder.time.setText(msg.getCreateDate().getHours() + ":" +
                    (msg.getCreateDate().getMinutes() < 10 ? "0" + msg.getCreateDate().getMinutes() : msg.getCreateDate().getMinutes()));
            mViewHolder.data.setText(msg.getCreateDate().getDate() + "");
            ImageLoader.getInstance().displayImage(msg.getBitmapUrls().get(0), mViewHolder.image, options);
            return convertView;
        }
    }

    private class ViewHolder2 {
        TextView headText;
        TextView secondText;
        ImageView pic;
        ProgressView playProgress;
        ImageView play;
        TextView audioTime;
        ProgressView loadingProgress;
    }

    private static final String[] MONTHS = new String[]{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};

    private class SetPlayProgress {
        public ProgressView mProgressView;
        public float progress;
    }

    MediaPlayer mPlayer;
    Timer mTimer;
    SetPlayProgress mSetPlayProgress;

    private class MyAdapter2 extends BaseAdapter {

        @Override
        public int getCount() {
            return messageModelArrayList.size();
        }

        @Override
        public Object getItem(int position) {
            return messageModelArrayList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater mInflater = LayoutInflater.from(mContext);
            ViewHolder2 mViewHolder = null;
            if (convertView == null) {
                mViewHolder = new ViewHolder2();
                convertView = mInflater.inflate(R.layout.square_item_2, null);
                mViewHolder.headText = (TextView) convertView.findViewById(R.id.head_text);
                mViewHolder.secondText = (TextView) convertView.findViewById(R.id.sencond_text);
                mViewHolder.pic = (ImageView) convertView.findViewById(R.id.pic);
                mViewHolder.play = (ImageView) convertView.findViewById(R.id.play_btn);
                mViewHolder.playProgress = (ProgressView) convertView.findViewById(R.id.progress);
                mViewHolder.audioTime = (TextView) convertView.findViewById(R.id.audio_time);
                mViewHolder.loadingProgress = (ProgressView) convertView.findViewById(R.id.play_loading);
                convertView.setTag(mViewHolder);
            } else {
                mViewHolder = (ViewHolder2) convertView.getTag();
            }
            final ReceiveMessageModel msg = messageModelArrayList.get(position);
            final ViewHolder2 finalMViewHolder = mViewHolder;
            mViewHolder.play.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final File audioFile = new File(mContext.getDir("audio_file", Context.MODE_PRIVATE), msg.getAudioFileId());
                    if (audioFile.exists()) {
                        finalMViewHolder.loadingProgress.stop();
                        finalMViewHolder.loadingProgress.setVisibility(View.GONE);
                        finalMViewHolder.play.setVisibility(View.VISIBLE);
                        try {
                            if (mTimer == null) {
                                mTimer = new Timer();
                            } else {
                                mTimer.cancel();
                                mTimer = new Timer();
                            }
                            if (mSetPlayProgress == null) {
                                mSetPlayProgress = new SetPlayProgress();
                            } else {
                                mSetPlayProgress.mProgressView.stop();
                            }
                            if (mPlayer == null) {
                                mPlayer = new MediaPlayer();
                            } else {
                                mPlayer.reset();
                            }
                            mPlayer.setDataSource(audioFile.getAbsolutePath());
                            mPlayer.prepare();
                            AudioUtil.muteAudioFocus(mContext, true);
                            mPlayer.start();
                            mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                                @Override
                                public void onCompletion(MediaPlayer mp) {
                                    AudioUtil.muteAudioFocus(mContext, false);
                                    mTimer.cancel();
                                    finalMViewHolder.playProgress.stop();
                                }
                            });
                            finalMViewHolder.playProgress.start();
                            mTimer.schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    Message msg = Message.obtain(mHandler);
                                    mSetPlayProgress.mProgressView = finalMViewHolder.playProgress;
                                    mSetPlayProgress.progress = (float) mPlayer.getCurrentPosition() / (float) mPlayer.getDuration();
                                    msg.obj = mSetPlayProgress;
                                    msg.sendToTarget();
                                }
                            }, 0, 1000);
                        } catch (Exception e) {
//                            Log.e(TAG, "播放失败");
                        }
                    } else {
                        finalMViewHolder.play.setVisibility(View.GONE);
                        finalMViewHolder.loadingProgress.setVisibility(View.VISIBLE);
                        finalMViewHolder.loadingProgress.start();
                        LeanCloudUtil.clearAudioFileCacheIfNecessary(mContext.getDir("audio_file", Context.MODE_PRIVATE));
                        LeanCloudUtil.getAudioFile(msg.getAudioFileId(), new GetDataCallback() {
                            @Override
                            public void done(byte[] bytes, AVException e) {
                                if (e == null) {
                                    try {
                                        FileOutputStream fs = new FileOutputStream(audioFile);
                                        fs.write(bytes, 0, bytes.length);
                                        fs.close();
                                        finalMViewHolder.play.setVisibility(View.VISIBLE);
                                        finalMViewHolder.play.performClick();
                                    } catch (IOException e1) {
                                        e1.printStackTrace();
                                    }
                                } else {
                                }
                            }
                        });
                    }
                }
            });
            mViewHolder.headText.setText(msg.getHead());
            mViewHolder.secondText.setText(MONTHS[msg.getCreateDate().getMonth()] + "  " + msg.getCreateDate().getDate() + "");
            ImageLoader.getInstance().displayImage(msg.getBitmapUrls().get(0), mViewHolder.pic, options);
            mViewHolder.pic.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent mIntent = new Intent(getActivity(), DetailActivity.class);
                    mIntent.putExtra("json", new Gson().toJson(msg));
                    startActivity(mIntent);
                }
            });
            mViewHolder.audioTime.setText(msg.getAudioTime() / 1000 + "'" + (msg.getAudioTime() % 1000 / 10 < 10 ? "0" + msg.getAudioTime() % 1000 / 10 : msg.getAudioTime() % 1000 / 10));
            return convertView;
        }
    }
}
